package cn.rengy.web.framework.web.log;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import cn.rengy.lang.DataConverter;
import cn.rengy.tool.web._WebUtils;

import lombok.extern.slf4j.Slf4j;

@Aspect
@Component
@Order(1)
@Slf4j
public class WebLogAspect {
    @Autowired
	private DataConverter dataConverter;
    //@Pointcut("execution(public * com.macro.mall.controller.*.*(..))")
    //@Pointcut("bean(*Controller)")
    @Pointcut("@annotation(org.springframework.web.bind.annotation.RequestMapping)")
    public void webLog() {
    }

//    @Before("webLog()")
//    public void doBefore(JoinPoint joinPoint) throws Throwable {
//    }

//    @AfterReturning(value = "webLog()", returning = "ret")
//    public void doAfterReturning(Object ret) throws Throwable {
//    }

    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        long startTime = System.nanoTime();
        //获取当前请求对象
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        //记录请求信息(通过Logstash传入Elasticsearch)
        
        Object result = joinPoint.proceed();
        Signature signature = joinPoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        Log logA=method.getAnnotation(Log.class);
        if(logA!=null) {
        	if(!logA.isLog())
        		return result;
        }
        WebLog webLog = new WebLog();
        //if (method.isAnnotationPresent(ApiOperation.class)) {
        //    ApiOperation log = method.getAnnotation(ApiOperation.class);
        //    webLog.setDescription(log.value());
        //}
        long endTime = System.nanoTime();
        webLog.setClientip(_WebUtils.getClientIp(request));
        webLog.setMethod(request.getMethod());
        webLog.setParameter(getParameter(method, joinPoint.getArgs()));
        webLog.setResult(result);
        webLog.setSpendTime((int)(endTime - startTime)/1000);
        webLog.setStartTime(startTime);
        webLog.setUrl(_WebUtils.getRequestURL(request));
        //Map<String,Object> logMap = new HashMap<>();
        //logMap.put("url",webLog.getUrl());
        //logMap.put("method",webLog.getMethod());
        //logMap.put("parameter",webLog.getParameter());
        //logMap.put("spendTime",webLog.getSpendTime());
        //logMap.put("description",webLog.getDescription());
        log.info(dataConverter.beanToJson(webLog));
        //LOGGER.info(Markers.appendEntries(logMap), JSONUtil.parse(webLog).toString());
        return result;
    }

    /**
     * 根据方法和传入的参数获取请求参数
     */
    private Object getParameter(Method method, Object[] args) {
        Parameter[] parameters = method.getParameters();
        if(parameters.length>0) {
        	List<Object> argList = new ArrayList<>(parameters.length);
            for (int i = 0; i < parameters.length; i++) {
            	Parameter param=parameters[i];
                //将RequestBody注解修饰的参数作为请求参数
                RequestBody requestBody = param.getAnnotation(RequestBody.class);
                if (requestBody != null) {
                    argList.add(args[i]);
                }
                //将RequestParam注解修饰的参数作为请求参数
                RequestParam requestParam = param.getAnnotation(RequestParam.class);
                if (requestParam != null){
                    Map<String, Object> map = new HashMap<>();
                    String key = param.getName();
                    if (StringUtils.hasLength(requestParam.value())){
                        key = requestParam.value();
                    }
                    //log.info(""+args[i].getClass());
                    if(args[i] instanceof MultipartFile) {
                    	map.put(key, "MultipartFile");
                    }else {
                    	map.put(key, args[i]);
                    }
                    
                    argList.add(map);
                }
            }
        	if (argList.size() == 1) {
                return argList.get(0);
            } else {
                return argList;
            }
        }
        return null;
    }
}
